package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.domain.Order;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    //体检预约
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) {
        //首先校验验证码
        String telephone = (String) map.get("telephone");
        //从redis中获取用户收到的验证码(5分钟内有效)
        Jedis jedis = jedisPool.getResource();
//        String validateCodeInRedis = jedis.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCodeInRedis = "f14a38";//测试
        String validateCode = (String) map.get("validateCode");
        jedis.close();
        if (validateCode != null && validateCode.equals(validateCodeInRedis)) {
            //用户输入的验证码正确,调用服务完成预约业务处理
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result = null;
            try {
                result = orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }

            //如果预约成功给用户发送短信(模拟一下)
            if (result.isFlag()) {
                System.out.println("恭喜您预约成功!");
            }
            return result;

        } else {
            //用户输入的验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        //System.out.println(id);
        try {
            Map map = orderService.findById(id);

            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
